import { Injectable, UnauthorizedException } from '@nestjs/common';
import { PassportStrategy } from '@nestjs/passport';
import { Strategy } from 'passport-local';
import { AuthService } from '../auth.service';
import { UsersService } from '../../users/users.service';
import { LoginUserDto } from '../../users/dto/login-user.dto';

@Injectable()
export class LocalStrategy extends PassportStrategy(Strategy) {
  constructor(
    private authService: AuthService,
    private usersService: UsersService,
  ) {
    super({
      usernameField: 'email',
      passwordField: 'password',
    });
  }

  async validate(email: string, password: string): Promise<any> {
    try {
      const loginDto: LoginUserDto = { email, password };
      const user = await this.usersService.validateUser(loginDto);
      if (!user) {
        throw new UnauthorizedException('邮箱或密码错误');
      }
      return user;
    } catch (error) {
      throw new UnauthorizedException('认证失败');
    }
  }
}
